<?php
namespace app\houtai\controller\user;

use app\houtai\controller\BaseController;
use app\houtai\controller\RedisHash;
use think\Db;
use think\Request;
use think\db\Expression;


class OnlineController extends BaseController {
  /**
   *  @brief  : 用户管理-在线用户
   *  @return : page
   *  @details: 
   */
  


  public function indexAction() {
   
    $conds = [];
    $order = [];
    $CHANNELS = $this->GetAdminChannel();
    $SHOWS = [0 => '全部显示', 1 => '显示分数', 2 => '显示得分'];
    $show = $this->request->param('show/d', 1);
    $show = array_key_exists($show, $SHOWS) ? $show : 0;
    //////////////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', 0);
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['u.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['u.Channel'][] = ['EQ', $channel];
    } else {
      $conds['u.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    //////////////////////////////////////////////////
    $SERVERID = [];
    $eax = table('CYBasicDB.dbo.UserOnline', 'rydb.basic')->query('SELECT DISTINCT a.ServerID, b.ServerName FROM CYBasicDB.dbo.UserOnline a LEFT JOIN CYBasicDB.dbo.GameRoomInfo b ON b.ServerID = a.ServerID ORDER BY b.ServerName');

    foreach($eax as $val) {
      $SERVERID[$val['ServerID']] = $val['ServerName'];
    }
    //////////////////////////////////////////////////
    $server = $this->request->param('server/d', -1);
    $server = array_key_exists($server, $SERVERID) ? $server : -1;
    if ($server > 0) {
      $conds['a.ServerID'] = $server;
    }
    //////////////////////////////////////////////////
    $time1 = $this->request->param('time1/s', '', 'trim,YmdHis2Unix');
    $time2 = $this->request->param('time2/s', '', 'trim,YmdHis2Unix');
    $ta = YmdHis($time1);
    $tb = YmdHis($time2);
    if ($time1 > 0) {
      if ($time2 > 0) {
        if ($time1 <= $time2) {
          $conds['a.CreateDate'] = ['BETWEEN TIME', [$ta, $tb]];
        } else {
          $conds['a.CreateDate'] = ['>= TIME', $ta];
        }
      } else {
        $conds['a.CreateDate'] = ['>= TIME', $ta];
      }
    } else {
      if ($time2 > 0) {
        $conds['a.CreateDate'] = ['<= TIME', $tb];
      }
    }
    //////////////////////////////////////////////////
    $search = $search = $this->request->param('search/s', '', 'trim');
    if (!empty($search)) {
      if (is_numeric($search) && $search > 0 && $search < PHP_INT_MAX) {
        $conds['a.UserID|u.GameID'] = $search;
      } else {
        $conds['u.NickName'] = ['LIKE', "%{$search}%"];
      }
    }
    $yqcode = $this->request->param('yqcode/d', 0);
    if ($yqcode > 0) {
      $conds['j.GameID'] = $yqcode;
    }
    //////////////////////////////////////////////////
    $time7 = YmdHis2Unix(date('Y-m-d 00:00:00'));
    $TMS = [
      [$time7 - 0 * 24 * 60 * 60, $time7 + 1 * 24 * 60 * 60], // day0
      [$time7 - 1 * 24 * 60 * 60, $time7 - 0 * 24 * 60 * 60],
      [$time7 - 2 * 24 * 60 * 60, $time7 - 1 * 24 * 60 * 60],
      [$time7 - 3 * 24 * 60 * 60, $time7 - 2 * 24 * 60 * 60],
      [$time7 - 4 * 24 * 60 * 60, $time7 - 3 * 24 * 60 * 60],
      [$time7 - 5 * 24 * 60 * 60, $time7 - 4 * 24 * 60 * 60],
      [$time7 - 6 * 24 * 60 * 60, $time7 - 5 * 24 * 60 * 60], // day6
      [$time7 - 6 * 24 * 60 * 60, $time7 + 1 * 24 * 60 * 60], // day7 合计
    ];
    $arr = [];
    foreach($TMS as $k => $v) {
      if ($show == 0 || $show == 1) {
        $key = sprintf("( SELECT ISNULL(SUM (g.lScore), 0) FROM [CYRecordDB].[dbo].[RecordGameDataChildUserRecord] g WHERE g.UserID = a.UserID  AND g.CreateTime BETWEEN '%s' AND '%s' )", YmdHis($v[0]), YmdHis($v[1]));
        $arr[$key] = "dayl{$k}";
      }
      if ($show == 0 || $show == 2) {
        $key = sprintf("( SELECT ISNULL(SUM (g.zScore), 0) FROM [CYRecordDB].[dbo].[RecordGameDataChildUserRecord] g WHERE g.UserID = a.UserID  AND g.CreateTime BETWEEN '%s' AND '%s' )", YmdHis($v[0]), YmdHis($v[1]));
        $arr[$key] = "dayz{$k}";
      }
    }
    if ($show == 0 || $show == 1) {
      $arr['( SELECT ISNULL(SUM (g.lScore), 0) FROM [CYRecordDB].[dbo].[RecordGameDataChildUserRecord] g WHERE g.UserID = a.UserID )'] = 'dayls';
    }
    if ($show == 0 || $show == 2) {
      $arr['( SELECT ISNULL(SUM (g.zScore), 0) FROM [CYRecordDB].[dbo].[RecordGameDataChildUserRecord] g WHERE g.UserID = a.UserID  )'] = 'dayzs';
    }
    //////////////////////////////////////////////////////////////////////////////////////
    $orderMap = [
      'A' => 'Channel',
      'B' => 'ServerID',
      'C' => 'TableNum',
      'D' => 'CreateDate',
      'E' => 'AGameID',
      'F' => 'Money',
      'G' => 'PlayCount',
      'H' => $show == 2 ? 'dayz6' : 'dayl6',
      'I' => $show == 2 ? 'dayz5' : 'dayl5',
      'J' => $show == 2 ? 'dayz4' : 'dayl4',
      'K' => $show == 2 ? 'dayz3' : 'dayl3',
      'L' => $show == 2 ? 'dayz2' : 'dayl2',
      'M' => $show == 2 ? 'dayz1' : 'dayl1',
      'N' => $show == 2 ? 'dayz0' : 'dayl0',
      'O' => $show == 2 ? 'dayz7' : 'dayl7',
      'P' => $show == 2 ? 'dayzs' : 'dayls',
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'D';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    //////////////////////////////////////////////////////////////////////////////////////
    $list = table('CYBasicDB.dbo.UserOnline a', 'rydb.basic')->field(array_merge([
      'a.UserID',  'a.ServerID', 'a.GameType', 'a.GameIp', 'a.Machine','a.KindID','b.GameName','a.TableNum',
      'a.CreateDate', 'b.GameName', 'c.ServerName', 'c.ServerType', 'w.Name' => 'ChannelName',
      'w.CustomID', 'u.GameID', 'u.Accounts', 'u.NickName', 'u.Compellation', 'u.PassPortID',
      'u.Sex', 'u.Channel', 'u.AccountsType', 'u.RegisterMobile', 'u.AccountImgUrl' => 'Avatar',
      'u.RegisterDate', 'u.RegisterIP', 'u.GameLogonCount', 'u.LastLogonDate', 'u.LastLogonIP',
      'j.RegisterMobile'=>'MobilePhone',
      'ISNULL(j.UserID, 0)' => 'AUserID',
      'ISNULL(j.GameID, 0)' => 'AGameID',
      'ISNULL(j.AccountsType, 0)' => 'AAccountsType',
      "ISNULL(j.Compellation, '')" => 'ACompellation',
      "ISNULL(j.AccountImgUrl, '')" => 'AAvatar',
      '( SELECT COUNT (g.RecordID) FROM [CYRecordDB].[dbo].[RecordCreateTable] g WHERE g.UserID = a.UserID AND g.ServerID = a.ServerID AND ( g.RecordType = 3 OR g.RecordType = 4 ))' => 'PlayCount', // 参与游戏次数
      '( CASE c.ServerType WHEN 16 THEN ( SELECT g.RoomCard FROM [CYBasicDB].[dbo].[AccountsGameCurrency] g WHERE g.UserID = a.UserID ) ELSE ( SELECT g.Gold FROM [CYBasicDB].[dbo].[AccountsGameCurrency] g WHERE g.UserID = a.UserID ) END )' => 'Money', // 统一房卡/统一金币/小游戏房卡数
    ], $arr))
    ->join('[CYBasicDB].[dbo].[GameKindItem] b',    'b.KindID = a.KindID', 'LEFT')
    ->join('[CYBasicDB].[dbo].[GameRoomInfo] c',    'c.ServerID = a.ServerID', 'LEFT')
    ->join('[CYBasicDB].[dbo].[AccountsInfo] u',    'u.UserID = a.UserID', 'LEFT')
    ->join('[CYBasicDB].[dbo].[ChannelConfig] w',     'w.ID = u.Channel', 'LEFT')
    ->join('[CYBasicDB].[dbo].[AccountsInfo] j',    'j.UserID = (SELECT g.SpreaderID FROM [CYBasicDB].[dbo].[AccountsInfo] g WHERE g.UserID = a.UserID)', 'LEFT')

    ->where($conds)->order($order)->paginate();
    //////////////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'list'    => $list,
      'search'  => $search,
      'channel' => $channel,
      'time1'   => $time1 <= 0 ? '' : YmdHis($time1),
      'time2'   => $time2 <= 0 ? '' : YmdHis($time2),
      'time7'   => $time7,
      'yqcode'  => $yqcode == 0 ? '' : $yqcode,
      'CHANNELS'=> $CHANNELS,
      'SERVERID'=> $SERVERID,
      'SHOWS'   => $SHOWS,
      'show'    => $show,
      'server'  => $server,
      'URL_GAME_INDEX'  => url('user.game/index'),
    ]);
  }
  /**
   *  @brief  : 用户管理-在线用户统计
   *  @return : page
   *  @details: 每天24各小时在线用户情况, (游戏记录+登陆记录)
   */
  public function trendAction() {
    $conds = [];
    $order = [];
    $CHANNELS = $this->GetAdminChannel();
    //////////////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', -1);
    if ($channel>0 && array_key_exists($channel, $CHANNELS)) {
      $conds['b.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['b.Channel'][] = ['EQ', $channel];
    } else {
      $conds['b.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    //////////////////////////////////////////////////////////////////////////////////////
    $orderMap = [
      'B' => 'Channel',
      'C' => 'GameID',
      'D' => 'TotalCount',
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'D';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    //////////////////////////////////////////////////////////////////////////////////////
    
    $sql2 = table('CYRecordDB.dbo.GameScoreLocker a', 'rydb.record')->field([
      'a.UserID','a.KindID','a.CreateDate','b.Channel','c.CustomID','a.SpreaderID',
    ])
    ->join('CYBasicDB.dbo.AccountsInfo b', 'b.UserID = a.UserID', 'LEFT')
    ->join('CYBasicDB.dbo.ChannelConfig c', 'c.ID = b.Channel', 'LEFT')
    ->join('CYBasicDB.dbo.AccountsGameCurrency d', 'd.UserID = a.UserID', 'LEFT')
    ->where($conds)
    ->buildSql();
    $sql2 = sql_pure($sql2);

    $sql3 = table("{$sql2} e", 'rydb.record')->field(['e.SpreaderID', 'COUNT(e.SpreaderID)' => 'TotalCount'])->group('e.SpreaderID')->buildSql();
    $sql3 = sql_pure($sql3);

    $list = table("{$sql3} f", 'rydb.record')->field([
      'f.SpreaderID', 'f.TotalCount', "ISNULL(c.Compellation, '')" => 'Compellation',
      'c.Channel', 'c.UserID', 'c.GameID', 'c.AccountImgUrl'=>'HeadImgUrl',
    ])
    ->join('CYBasicDB.dbo.AccountsInfo c', 'c.UserID = f.SpreaderID', 'LEFT')
    ->order($order)
    ->paginate();
    
    $TotalOnline = table("{$sql3} f", 'rydb.record')->sum('TotalCount');

    //////////////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'list' => $list,
      'channel' => $channel,
      'CHANNELS' => $CHANNELS,
      'TotalOnline' => $TotalOnline,
    ]);
  }
  /**
   *  @brief  : 清理单个用户
   *  @return : JSON
   *  @details: 
   */
  public function clearAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $GameID = $this->request->param('GameID/d', -1);
    if ($GameID <= 0) {
      return result([], 101, '业务参数无效');
    }
    $UserID = table('AccountsInfo', 'rydb.basic')->where('GameID', $GameID)->value('UserID');
    if ($UserID <= 0) {
      return result([], 102, "用户不存在GameID={$GameID}");
    }
    $eax = table('UserOnline', 'rydb.basic')->where('UserID', $UserID)->delete ();
    return result([], 0);
  }
}
